import React, {useState} from 'react'
import {api2, csrf, login} from '../api';

import PropTypes from 'prop-types'

import './sign-in9.css'
import {NavLink, useHistory} from "react-router-dom";

const SignIn9 = (props) => {

  props = {
    rootClassName: '',
    heading1: 'Войти',
    action1: 'Войти',
    action2: 'Create an account',
    content1: "Don't have an account?",
    ...props
  }

  const history = useHistory();


  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [error, setError] = useState(false);
  const [errorText, setErrorText] = useState('');
/*  const handleSubmit = async (e) => {
    e.preventDefault();
    await csrf();
    try {
      const response = await login({ email, password });
      console.log('User logged in:', response.data);
    } catch (error) {
      console.error('Error logging in:', error);
    }
  };*/

  const handleSubmit = async (e) => {
    e.preventDefault();
    try {
      const response = await api2.send('login', {email, password});
      if (response.success) {
        setError(false)
        localStorage.setItem('token', response.data.token);
        localStorage.setItem('user', JSON.stringify(response.data.user));
        // window._LC_._user = response.data.user;
        history.push('/home');
      } else {
        setErrorText('Неправильный логин/пароль')
        setError(true)
        console.error('Login failed:', response.error);
      }
    } catch (error) {
      setError(true)
      setErrorText('Ошибка сети, попробуйте еще раз')
      console.error('Error logging in:', error);
    }
  };

  return (
    <div
      className={`sign-in9-container thq-section-padding ${props.rootClassName} `}
    >
      <div className="sign-in9-max-width thq-section-max-width">
        <div className="sign-in9-container1">
          <h2 className="sign-in9-text thq-heading-2">{props.heading1}</h2>
        </div>
        <div className="sign-in9-container2">
          <div className="sign-in9-container3">
            <form onSubmit={handleSubmit} className="sign-in9-form">
              <div className="sign-in9-email">
                <label htmlFor="thq-sign-in-9-email" className="thq-body-large">
                  Электронная почта
                </label>
                <input
                    type="email"
                    id="thq-sign-in-9-email"
                    value={email}
                    onChange={(e) => setEmail(e.target.value)}
                    required={true}
                    placeholder="Ваша почта"
                    className="sign-in9-textinput thq-body-large thq-input"
                />
              </div>
              <div className="sign-in9-password">
                <div className="sign-in9-container4">
                  <label
                      htmlFor="thq-sign-in-9-password"
                      className="thq-body-large"
                  >
                    Пароль
                  </label>
                  <div className="sign-in9-hide-password"></div>
                </div>
                <input
                    type="password"
                    id="thq-sign-in-9-password"
                    required={true}
                    placeholder="Ваш пароль"
                    value={password}
                    onChange={(e) => setPassword(e.target.value)}
                    className="sign-in9-textinput1 thq-body-large thq-input"
                />
              </div>
              <button
                  type="submit"
                  className="sign-in9-button thq-button-filled"
              >
                <span className="sign-in9-text3 thq-body-small">
                  {props.action1}
                </span>
              </button>
            </form>
            {error && <p className="sign-in9-text5 thq-body-large">{errorText}</p>}
          </div>
          <div className="sign-in9-divider">
            <div className="sign-in9-container5">
              <div className="sign-in9-divider1"></div>
              <span className="thq-body-large">Или</span>
              <div className="sign-in9-divider2"></div>
            </div>
            <p className="sign-in9-text5 thq-body-large">Не можете войти?</p>
          </div>
          <div className="sign-in9-container6">
            <div className="sign-in9-container7">
              <NavLink to="/register"  >
              <button className="sign-in9-button1 thq-button-outline">
                <span className="thq-body-small">Зарегестрироваться</span>
              </button>
              </NavLink>
            </div>
          </div>
          <div className="sign-in9-container6">
            <div className="sign-in9-container7">
              <button className="sign-in9-button1 thq-button-outline">
                <span className="thq-body-small">Войти через Госуслуги</span>
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  )
}

export default SignIn9
